package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.model.LatLng;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.MainActivity;
import com.srwl.mytx.activity.PublishTopicActivity;
import com.srwl.mytx.activity.TopicSearchActivity;
import com.srwl.mytx.adapter.HomePageTopicAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2016/8/23 0023.
 */
public class HomePageTextFragment extends BaseFragment implements View.OnClickListener {
    public static final int REQUESTCODE_EDIT_TOPIC = 1;
    private static final String TAG = HomePageTextFragment.class.getSimpleName();
    private static final int MODE_HOTEST = 0;
    private static final int MODE_NEARBY = 1;
    private static final int MODE_ATTENTION = 2;
    private int currentMode;
    private ProgressBar progressBar;
    private View view;
    private ImageView iv_release;
    private TextView tv_first_title;
    private TextView tv_second_title;
    private TextView tv_third_title;
    private MaterialSmoothRefreshLayout refreshLayout;
    protected boolean hidden;
    private RelativeLayout rl_search;
    // private RelativeLayout rl_topBar;
    private ImageView switch_text;
    private RecyclerView textListRecyclerView;
    private HomePageTopicAdapter topicAdapter;
    private List<Topic> topicList = new ArrayList<>();
    private MainActivity.ChangeFragmentListener listener;
    private int page = 1;
    private int size = 10;
    private boolean hasNextPage;
    private LatLng locationLatLon;

    public void setListener(MainActivity.ChangeFragmentListener listener) {
        this.listener = listener;
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_page_text_list, container, false);
        progressBar = view.findViewById(R.id.progress_bar);
        switch_text = view.findViewById(R.id.iv_switch);
        switch_text.setOnClickListener(this);
        iv_release = view.findViewById(R.id.iv_release);
        iv_release.setOnClickListener(this);
        rl_search = view.findViewById(R.id.rl_search);
        // rl_topBar = view.findViewById(R.id.rl_top_bar);
        tv_first_title = view.findViewById(R.id.tv_first_title);
        tv_second_title = view.findViewById(R.id.tv_second_title);
        tv_third_title = view.findViewById(R.id.tv_third_title);
        rl_search.setOnClickListener(this);
        tv_first_title.setOnClickListener(this);
        tv_second_title.setOnClickListener(this);
        tv_third_title.setOnClickListener(this);
        textListRecyclerView = view.findViewById(R.id.text_list);
        refreshLayout = view.findViewById(R.id.refresh_layout);
        initRefreshLayout();
        location();
        topicAdapter = new HomePageTopicAdapter(getContext(), topicList);
        textListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        textListRecyclerView.setAdapter(topicAdapter);
        topicAdapter.showNoDataView();
        loadHottestTopicData(false, true);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    private void location() {
        GaodeLocationClient location = new GaodeLocationClient(getContext());
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(AMapLocation amapLocation) {
                double latitude = amapLocation.getLatitude();//获取纬度
                double longitude = amapLocation.getLongitude();//获取经度
                locationLatLon = new LatLng(latitude, longitude);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_release:
//                String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//                if (TextUtils.isEmpty(phoneNumber)) {
//                    ConfirmDialog confirmDialog = new ConfirmDialog(getContext(), "提示", "绑定手机号才可以发布主题，去绑定？", true);
//                    confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                        @Override
//                        public void confirm() {
//                            startActivity(new Intent(getActivity(), UpdateUserInfoActivity.class));
//                        }
//                    });
//                    confirmDialog.show();
//                } else {
//                }
                startActivity(new Intent(getActivity(), PublishTopicActivity.class));
                break;
            case R.id.tv_first_title:
                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_first_title.setTextColor(Color.parseColor("#2e2e2e"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_second_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_third_title.setTextColor(Color.parseColor("#8E8E8E"));
                currentMode = MODE_HOTEST;
                refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                page = 1;
                loadHottestTopicData(true, true);
                break;

            case R.id.tv_second_title:
                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_first_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_second_title.setTextColor(Color.parseColor("#2e2e2e"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_third_title.setTextColor(Color.parseColor("#8E8E8E"));
                currentMode = MODE_NEARBY;
                refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                page = 1;
                nearbySearch(true, true);
                break;
            case R.id.tv_third_title:
                tv_first_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_first_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_second_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_other_title));
                tv_second_title.setTextColor(Color.parseColor("#8E8E8E"));
                tv_third_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimensionPixelSize(R.dimen.on_the_show_title));
                tv_third_title.setTextColor(Color.parseColor("#2e2e2e"));
                currentMode = MODE_ATTENTION;
                refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                page = 1;
                // TODO: 2019/4/16 查询我关注的主题


                break;
            case R.id.iv_switch:
                if (listener == null) {
                    return;
                } else {
                    listener.onChangeFragment();
                }
                break;
            case R.id.rl_search:
                startActivity(new Intent(getActivity(), TopicSearchActivity.class));
                break;
        }
    }

    private void loadHottestTopicData(boolean isRefresh, boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if(!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", size);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .queryHottestTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }

                        Object data = result.getData();
                        if (data == null) {
                            return;
                        }
                        JSONArray jsonArray = (JSONArray) data;
                        Log.d(TAG, "onResponse: " + jsonArray.toJSONString());
                        List<Topic> topics = null;
                        try {
                            topics = jsonArray.toJavaList(Topic.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (topics == null || topics.size() == 0) {
                            hasNextPage = false;
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);


                            return;
                        }
                        if (topics.size() < size) {
                            hasNextPage = false;
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);

                        } else {
                            hasNextPage = true;
                        }
                        if (isRefresh) {
                            topicList.clear();
                        }
                        topicList.addAll(topics);
                        topicAdapter.showNormalView();
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, t.getMessage());
                    }
                });

    }

    void initRefreshLayout() {
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);

        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                switch (currentMode) {
                    case MODE_HOTEST:

                        loadHottestTopicData(true, false);
                        break;
                    case MODE_NEARBY:
                        nearbySearch(true, false);
                        break;
                    case MODE_ATTENTION:

                        break;
                }
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    switch (currentMode) {
                        case MODE_HOTEST:
                            loadHottestTopicData(false, false);
                            break;
                        case MODE_NEARBY:
                            nearbySearch(false, false);
                            break;
                        case MODE_ATTENTION:

                            break;
                    }
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUESTCODE_EDIT_TOPIC) {
            Topic topic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
            //因为聊天室如果为未审核通过情况下,会存在删除或者编辑,所以给定一个标记用于判断是删除操作还是编辑操作
            refreshTopic(topic);
        }
    }

    public void refreshTopic(Topic topic) {
        for (int i = 0; i < topicList.size(); i++) {
            if (TextUtils.equals(topicList.get(i).getId(), topic.getId())) {
                topicList.set(i, topic);
                topicAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;

    }


    private void nearbySearch(boolean isRefresh, boolean isFirst) {
        if (locationLatLon == null) {
            showToast("定位失败");
            return;
        }

        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }

        Map<String, Object> body = new HashMap<>();
        body.put("lat", locationLatLon.latitude);
        body.put("lon", locationLatLon.longitude);
        body.put("distance", 10);
        body.put("page", page);
        Log.d(TAG, "page: 第" + page + "页数据");
        body.put("size", size);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .nearbySearch(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES附近搜索失败：" + response.message());
                            topicAdapter.showErrorView();
                            return;

                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES附近搜索失败：" + result.getMsg());
                            topicAdapter.showErrorView();
                            return;
                        }


                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES附近搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        Integer total = jsonObject.getInteger("total");
                        Log.d(TAG, "total: 全部主题共" + total + "条");
                        hasNextPage = page * size < total;

                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        if (resultsList == null || resultsList.size() == 0) {
                            topicAdapter.showNoDataView();
                            return;
                        }
                        if (isRefresh) {
                            topicList.clear();
                        }
                        topicList.addAll(resultsList);
                        Log.d(TAG, "共" + topicList.size() + "条" + jsonObject);
                        topicAdapter.showNormalView();
                        page++;

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        topicAdapter.showErrorView();
                    }
                });
    }


    private void showProgressBar(boolean isShowProgressBar) {
        if (isShowProgressBar && !progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!isShowProgressBar && progressBar.isShown()) {
            progressBar.setVisibility(View.GONE);
        }
    }


}

